package controllers

import (
	"net/http"
	"strconv"
	"strings"
	"time"

	"bankend/database"
	"bankend/models"

	"github.com/gin-gonic/gin"
)

// GetAutoReplies 根据查询参数模糊搜索自动回复规则（只返回未软删除记录）
// GET /api/auto_replies?q=关键词
func GetAutoReplies(c *gin.Context) {
	query := c.Query("q")
	var replies []models.AutoReply
	db := database.DB
	if query != "" {
		pattern := "%" + strings.TrimSpace(query) + "%"
		db.Where("deleted_at IS NULL").
			Where("keyword LIKE ? OR reply_content LIKE ?", pattern, pattern).
			Find(&replies)
	} else {
		db.Where("deleted_at IS NULL").Find(&replies)
	}
	c.JSON(http.StatusOK, gin.H{"auto_replies": replies})
}

// GetAutoReply 根据 ID 获取单个自动回复规则
// GET /api/auto_replies/:id
func GetAutoReply(c *gin.Context) {
	idParam := c.Param("id")
	id, err := strconv.Atoi(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的规则ID"})
		return
	}
	var reply models.AutoReply
	if err := database.DB.Where("reply_id = ? AND deleted_at IS NULL", id).First(&reply).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "自动回复规则不存在"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"auto_reply": reply})
}

// CreateAutoReply 创建新的自动回复规则
// POST /api/auto_replies
func CreateAutoReply(c *gin.Context) {
	var reply models.AutoReply
	if err := c.ShouldBindJSON(&reply); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	reply.CreateTime = time.Now()
	if err := database.DB.Create(&reply).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusCreated, gin.H{"auto_reply": reply})
}

// UpdateAutoReply 更新自动回复规则
// PUT /api/auto_replies/:id
func UpdateAutoReply(c *gin.Context) {
	idParam := c.Param("id")
	id, err := strconv.Atoi(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的规则ID"})
		return
	}
	var reply models.AutoReply
	if err := database.DB.Where("reply_id = ? AND deleted_at IS NULL", id).First(&reply).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "自动回复规则不存在"})
		return
	}
	var updated models.AutoReply
	if err := c.ShouldBindJSON(&updated); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	// 保留原始数据，更新必要的字段
	updated.ReplyID = reply.ReplyID
	updated.CreateTime = reply.CreateTime
	if err := database.DB.Model(&reply).Updates(updated).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"auto_reply": reply})
}

// DeleteAutoReply 软删除自动回复规则
// DELETE /api/auto_replies/:id
func DeleteAutoReply(c *gin.Context) {
	idParam := c.Param("id")
	id, err := strconv.Atoi(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的规则ID"})
		return
	}
	now := time.Now()
	if err := database.DB.Model(&models.AutoReply{}).
		Where("reply_id = ? AND deleted_at IS NULL", id).
		Update("deleted_at", now).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "自动回复规则已软删除"})
}

// ProcessAutoReply 根据用户输入的消息内容查找匹配的自动回复规则
// 若匹配不到，则预留位置调用外部 API（例如调用聊天机器人接口）进行回复
// POST /api/auto_replies/process
func ProcessAutoReply(c *gin.Context) {
	// 请求示例：{"message": "你好", "platform": "wechat"}
	var req struct {
		Message  string `json:"message"`
		Platform string `json:"platform"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	// 优先在数据库中查找匹配的自动回复规则（这里为精确匹配，可根据需要改为模糊匹配）
	var reply models.AutoReply
	if err := database.DB.Where("deleted_at IS NULL AND platform = ? AND status = ?", req.Platform, "启用").
		Where("keyword = ?", req.Message).
		First(&reply).Error; err != nil {
		// TODO: 当未匹配到自动回复规则时，可调用外部 API 实现自动回复
		// 示例：replyText := CallExternalAPI(req.Message)
		// 目前返回默认回复
		c.JSON(http.StatusOK, gin.H{"reply": "对不起，我无法理解您的请求。"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"reply": reply.ReplyContent})
}

// 注意：外部 API 调用函数示例（预留接口）
// func CallExternalAPI(message string) string {
//     // TODO: 实现调用外部自动回复 API 的逻辑
//     // 例如调用第三方聊天机器人接口，解析返回内容后返回回复文本
//     return "外部API回复内容"
// }
